<template>
  <div class="callarea" v-loading="loading">
    <div class="top">
        <div class="search">
          <div class="contition">
            <div class="wrap_time">
              <date-time type="other_half_hour" @changeType="changeType" ref="child" :query="query" @isFold="isShowFold" :isTimePeriod = "true" :isOther="true"></date-time>
              <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search">{{$t('public.search2')}}</el-button></div>
            <div class="clear"></div>
            <div class="wrap_drop">
              <unfold :isShow="isFold" :title="[]">
                <template slot="unfoldSlot">
                   <div class="serve">
                    <span class="colo">{{$t('monitor.serviceNum')}}：</span>
                    <el-checkbox v-model.trim="checkAll" @change="handleServiceNosCheckAll">{{$t('public.checkAll')}}</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model.trim="checkedServiceNos" @change="handleServiceNosCheck">
                      <el-checkbox v-for="(number, index) in serviceNos" :label="number.Exten" :value="number.Exten" :key="index">{{number.Exten}}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                  <div class="serve serve1">
                    <span class="pro colo">{{$t('public.province')}}：</span>
                    <el-checkbox :indeterminate="isIndeterminate1" v-model.trim="checkAll1" @change="handleProvincesCheckAll">{{$t('public.checkAll')}}</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model.trim="checkedProvinces" @change="handleProvincesCheck">
                      <el-checkbox v-for="(province, index) in provinces" :label="province" :name="province" :key="index">{{province}}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </template>
              </unfold>
            </div>
          </div>
        </div>
        <affix :label="$t('report.callInAreaSurvey')"></affix>
        <div class="situation">
          <div class="wrap_pro">
            <div class="call_all">
              <span>{{$t('monitor.inCallSum')}}</span>
              <span class="all_num">{{callInAll}}</span>
            </div>
            <div class="wrap_top" v-show="serveNumData.length !== 0">
              <span>{{$t('report.callInTopPro')}}</span>
              <ul>
                <li v-for="(item, index) in situation" :key="index">
                  <span class="sum_name">{{item.name}}</span>
                  <span class="sit_num">{{item.value}}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <affix :label="$t('report.relaycallDisCity')"></affix>
        <div class="clear"></div>
      </div>
    <div class="tab" :id="id">
      <div class="export">
        <el-button class="primary_btn fr" v-on:click.stop="config" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

        <!-- <el-button class="primary_btn fr report_excel_btn"
          v-if="$store.getters.exportFromEnd"
          v-on:click.stop="exportExcel"
        >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

        <el-button class="primary_btn fr report_excel_btn"
          v-on:click.stop="searchOrExport(true)"
        >{{$t('report.exportXls')}}</el-button>

        <el-button class="primary_btn fr pdf" v-on:click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        <el-button class="primary_btn fr pdf" v-on:click.stop="flag">{{$t('report.returnPreviousPage')}}</el-button>
      </div>
      <report-table :data="serveNumData" :sum="sum" :config="headOptions.Config"> </report-table>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <header-option v-show="isShow" :show="isShow" :option="headOptionsShow" type="call_report_relay_area_city" v-on:close="close"></header-option>
  </div>
</template>
<script>
  import dateTime from '../base/datetime.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import headerOption from '../base/headerOption.vue'
  import reportTable from '../base/drillInto.vue'
  import {exportReportPdf, checkTime, searchTime, headOptionsToXlsxHeaders, reportAreaProvince} from '@/utils/reportUtils.js'
  import {getCache, deepClone, getCallTimeLength, optionTimeTypeCheck} from '@/utils/m7Utils.js'
  import affix from '../../../ui-modules/affix/Affix.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'

  export default {
    name: 'callarea',
    data () {
      return {
        dateType: 'day',
        isFold: false, // 是否展示搜索条件
        situation: [], // 概况渲染数据
        callInAll: 0, // 呼入总数
        loading: false, // 查询时展示加载的开关
        id: 'call_report_relay_area_city', // 查询id
        query: { // 查询条件时间信息等
          reportType: '',
          relayAreaCityCurrentProvince: this.cityName.cityName
        },
        checkAll: true, // 服务号全选绑定值
        checkAll1: true, // 省份全选绑定值
        checkedServiceNos: [], // 服务号绑定值
        checkedProvinces: [], // 省份绑定值
        headOptionsShow: {}, // 配置表头数据
        headOptions: { // 表头数据
          Config: []
        },
        isShow: false, // 是否展示配置表头开关
        dialogVisible: false, // 导出pdf弹窗开关
        serviceNos: [], // 服务号数据
        provinces: reportAreaProvince, // 省份数据
        isIndeterminate: false, // 全选样式调控值
        isIndeterminate1: false, // 全选样式调控值
        sum: [], // 表格合计数据
        serveNumData: [] // 表格table除合计数据
      }
    },
    props: [
      'cityName', 'parentDateType'
    ],
    methods: {
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 返回上页
      flag () {
        // this.cityName.cityName = ''
        this.$emit('flag')
      },
      // 渲染服务号和省
      condition () {
        let self = this
        this.provinces.forEach(function (item) {
          if (self.checkedProvinces.indexOf(item) >= 0) {
            self.query['Province_' + item] = true
          } else {
            self.query['Province_' + item] = false
          }
        })
        self.serviceNos.forEach(function (item) {
          if (self.checkedServiceNos.indexOf(item.Exten) >= 0) {
            self.query['ServiceNo_' + item.Exten] = true
          } else {
            self.query['ServiceNo_' + item.Exten] = false
          }
        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx (headOptions, tempData, sum) {
        var headers = headOptionsToXlsxHeaders(headOptions.Config)

        var tableData = tempData.concat(sum)

        var dh = XlsxUtil.getDownloadHelper(headers, tableData)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download(this.$t('report.callReportRelayArea') + timeStamp)
      },
      // 查询或导出excel
      searchOrExport (isExport) {
        // 判断服务号和省是否为空
        if (this.checkedServiceNos.length === 0) {
          this.open3()
          return
        }
        if (this.checkedProvinces.length === 0) {
          this.open2()
          return
        }
        let data = {
          reportType: 'call_report_relay_area_city',
          account: this.$store.state.session.user.account
        }
        this.condition()
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          // 校验类型与时间
          let message = null
          if (this.dateType === 'week') { // 周报允许到天
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          } else {
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          }
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        if (myQuery.TimeType === 'year') {
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        delete myQuery.relayAreaCityCurrentProvince
        data.query = myQuery
        this.loading = true

        this.$store.dispatch('openRelayAreaCity', data).then((res) => {
          if (!res.success) {
            this.loading = false
            return
          }
          this.loading = false
          var situation = []
          var sum = [{City: this.$t('report.total')}]
          var headOptions = optionTimeTypeCheck(res.tableHeader)

          let tempData = deepClone(res.data)
          if (tempData.length !== 0) {
            sum = [{City: this.$t('report.total')}]
          } else {
            sum = [{}]
            if (isExport) {
              this.exportXlsx(headOptions, tempData, sum)
            } else {
              // 初始化页面展示数据
              this.sum = sum
              this.callInAll = 0
              this.headOptions = headOptions
              this.serveNumData = tempData
              this.headOptions = headOptions
              this.situation = situation
            }
            return
          }

          for (let i in tempData) {
            let item = tempData[i]
            // 渲染概况 渲染前五得省份
            if (i < 5) {
              situation.push({name: item._id, value: item.AccessCount})
            }
            for (let j in item) {
              if (sum[0][j] === undefined) {
                sum[0][j] = 0
              }
              if (j !== 'City') {
                sum[0][j] += item[j]
              }
            }
            headOptions.Config.forEach((option, index) => {
              if (option.timeType && option.timeType === 'hhmmss') {
                item[option.name] = getCallTimeLength(item[option.name])
              } else if (option.timeType && option.timeType === 'second') {
                item[option.name] = Math.round(item[option.name]) + 's'
              }
            })
          }
          headOptions.Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              sum[0][option.name] = getCallTimeLength(sum[0][option.name])
            } else if (option.timeType && option.timeType === 'second') {
              sum[0][option.name] = Math.round(sum[0][option.name]) + 's'
            }
          })
          if (isExport) {
            this.exportXlsx(headOptions, tempData, sum)
          } else {
            this.sum = sum
            this.callInAll = this.sum[0].AccessCount || 0
            this.headOptions = headOptions
            this.serveNumData = tempData
            this.headOptions = headOptions
            this.situation = situation
          }
        })
      },
      // 查询报表数据
      search () {
        this.searchOrExport()
      },
      // 子组件切换时间类型传上来得方法 触发计算属性
      changeType (type) {
        this.dateType = type
      },
      // 钻入进来执行的方法
      search1 () {
        // 从父组件获取数据计算初始查询条件
        this.dateType = this.parentDateType || 'day'
        this.checkedProvinces = [this.cityName.cityName]
        this.checkedServiceNos = this.cityName.checkedServiceNos
        // 给时间插件赋值
        this.$refs.child.form = {
          timeType: this.cityName.queryOne.TimeType,
          yearReport: parseInt(this.cityName.queryOne.yearReport),
          monthReport: parseInt(this.cityName.queryOne.monthReport),
          dayReport: parseInt(this.cityName.queryOne.dayReport)
        }
        if (this.cityName.dateSource.timeType) {
          this.$refs.child.week = this.cityName.dateSource.week
          this.$refs.child.form.timeType = this.cityName.dateSource.timeType
        }
        this.query = deepClone(this.cityName.queryOne)
        // 赋初始值 渲染时间组件
        this.$refs.child.formSource = this.cityName.dateSource
        this.$refs.child.timeCheck = this.cityName.queryOne.timePeriod || false
        this.$refs.child.timePeriodStart = this.cityName.queryOne.timePeriodStart || ''
        this.$refs.child.timePeriodEnd = this.cityName.queryOne.timePeriodEnd || ''
        // 如果时间为自定义
        if (this.cityName.queryOne.TimeType === 'other_half_hour') {
          if (this.cityName.queryOne.StartTime || this.cityName.queryOne.EndTime) {
            let StartTime = this.cityName.queryOne.StartTime.split(' ')[1] ? this.cityName.queryOne.StartTime.split(' ')[1] : ''
            let EndTime = this.cityName.queryOne.EndTime.split(' ')[1] ? this.cityName.queryOne.EndTime.split(' ')[1] : ''
            this.$refs.child.otherTimes = {
              beginTime: StartTime,
              endTime: EndTime,
              beginDate: this.cityName.queryOne.normalStartTime,
              endDate: this.cityName.queryOne.normalEndTime
            }
          } else {
            this.$refs.child.otherTimes = {
              beginTime: '',
              endTime: '',
              beginDate: '',
              endDate: ''
            }
          }
        }
        if (this.query.TimeType === 'other_half_hour') {
          let message = null
          if (this.dateType === 'week') { // 周报允许到天
            message = checkTime(this.query.StartTime, this.query.EndTime, false, true) // 校验类型与时间
          } else {
            message = checkTime(this.query.StartTime, this.query.EndTime, false, false) // 校验类型与时间
          }
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        // 初始化查询条件
        this.query = deepClone(this.cityName.queryOne)
        this.query.relayAreaCityCurrentProvince = this.cityName.cityName
        this.query.reportType = 'call_report_relay_area'
        this.query.timeType = this.query.TimeType
        this.searchOrExport()
      },
      // 获取表头数据
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.search()
        }
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.callReportRelayCity') + searchTime(this.query), id: this.id})
      },
      // 导出表格数据执行的方法(后端)
      exportExcel () {
        this.condition()
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        // 转换timeType
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        if (myQuery.TimeType === 'year') {
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        myQuery.reportType = 'call_report_relay_area_city'
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.type = 'ReportRelayAreaCityExport'
        myQuery.user = this.$store.state.session.user._id
        delete myQuery.relayAreaCityCurrentProvince
        let data = {
          Method: 'ReportRelayAreaCityExport',
          Query: myQuery
        }
        this.$store.dispatch('exportCallRelayAreaReport', data).then(() => {
        })
      },
      // 配置表头
      config () {
        this.$store.dispatch('getReportTableHeader', 'call_report_relay_area_city').then((res) => {
          this.headOptionsShow = optionTimeTypeCheck(res)
          this.isShow = !this.isShow
        })
      },
      // 判断查询条件是否为空
      open3 () {
        this.$message.error(this.$t('report.searchBathnos'))
      },
      open2 () {
        this.$message.error(this.$t('report.searchProvince'))
      },
      // 全选，参考饿了么
      handleServiceNosCheckAll (event) {
        this.checkedServiceNos = []
        if (this.checkAll === true) {
          this.serviceNos.forEach((i) => {
            this.checkedServiceNos.push(i.Exten)
          })
        }
      },
      // 选择服务号判断是否勾选全选
      handleServiceNosCheck (value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.serviceNos.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.serviceNos.length
      },
      // 点击全选触发的方法
      handleProvincesCheckAll (event) {
        this.checkedProvinces = this.checkAll1 ? this.provinces : []
        this.isIndeterminate1 = false
      },
      // 点击选择省份触发的方法 参数选择省份值[]
      handleProvincesCheck (value) {
        let checkedCount = value.length
        this.checkAll1 = checkedCount === this.provinces.length
        this.isIndeterminate1 = checkedCount > 0 && checkedCount < this.provinces.length
      }
    },
    watch: {
      // cityName (cur) {
      //   console.log(cur, 66666)
      //   if (cur.cityName && cur.switchTem) {
      //     this.search1()
      //   }
      // }
    },
    computed: {
      // 判断是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      }
    },
    components: {
      unfold,
      dateTime,
      headerOption,
      reportTable,
      affix
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'serviceNo'}).then(() => {
        this.serviceNos = getCache('serviceNo')
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .callarea
    .tab
      margin-top 0
    .el-checkbox-group
      margin-left 40px
      .el-checkbox
        width 90px
        margin-left 12px
        &:nth-child(1)
          padding-left 12px
          margin-left 0
</style>
